from http.server import BaseHTTPRequestHandler,HTTPServer
import sys,os
class ServerException(Exception):
    '''服务器内部错误'''
    pass

class RequestHandler(BaseHTTPRequestHandler):
    Page = '''\
               <html>
               <body>
               <table>
               <tr>  <td>Header1</td>         <td>Value</td>              </tr>
               <tr>  <td>Date and time</td>   <td>{date_time}</td>        </tr>
               <tr>  <td>Client host</td>     <td>{client_host}</td>      </tr>
               <tr>  <td>client port</td>     <td>{client_port}</td>      </tr>
               <tr>  <td>conmand</td>         <td>{command}</td>          </tr>
               <tr>  <td>Path</td>            <td>{path}</td>             </tr>
               </table>
               </body>
               </html>'''
    error_page = '''\
                <html>
                <body>
                <h1>Error accessing {path}</h1>
                <p>{msg}</p>
                </body>
                </html>
                '''
    def do_GET(self):
        # page = self.create_page()
        # self.send_content(page)
        try:
            #完整路径
            full_path = os.getcwd() + self.path
            print(full_path)
            #文件未找到
            if not os.path.exists(full_path):
                raise ServerException("'{0}' not found".format(self.path))
            #是一个文件
            elif  os.path.isfile(full_path):
                self.handle_file(full_path)
            #不是文件
            else:
                raise ServerException("Unknow object'{0}'".format(self.path))
        except Exception as msg:
            self.handle_error(msg)
    #发送错误信息
    def handle_error(self,msg):
        content = self.error_page.format(path =self.path,msg=msg)
        self.send_content(content.encode('utf-8'))
    #判断or发送文件内容
    def handle_file(self,full_path):
        try:
            with open(full_path,'rb') as file:
                content = file.read()
            self.send_content(content)
        except IOError as msg:
            msg = "{0} can not be read{1}".format(self.path,msg)
            self.handle_file(msg)
    #设计页面
    def create_page(self):
        values = {
            "date_time":  self.date_time_string(),
            'client_host': self.client_address[0],
            'client_port': self.client_address[1],
            'command'    : self.command,
            'path'       : self.path
        }
        page = self.Page.format(**values)
        return page
    def send_content(self,page):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.send_header("Content-Length", str(len(self.Page)))
        self.end_headers()
        self.wfile.write(self.Page.encode('utf-8'))
if __name__ == '__main__':
    serverAddress = ('', 8010)
    server = HTTPServer(serverAddress, RequestHandler)
    server.serve_forever()
